﻿$(function () {
    $('#categoryList').combotree({
        onCheck: function (node, checked) {
            var t = $('#categoryList').combotree('tree');	// get the tree object
            var nodes = t.tree('getChecked');
            var predArray = [];
            //predArray.push(breeze.Predicate.create('CategoryId', '==', '00000'));
            for (i = 0; i < nodes.length; i++) {
                predArray.push(nodes[i].id);
            }
            var queryQuestion = new breeze.EntityQuery().from("QuestionList").withParameters({categories: predArray});
            loadQuestion(queryQuestion);
            var queryAnswer = new breeze.EntityQuery().from("AnswerList").withParameters({ categories: predArray });
            loadAnswer(queryAnswer);
        },
        onBeforeExpand: function (node) {
            exploreNode(node, false, 'categoryList');
        }
        
    });

});
function exploreNode(node, intab, id) {
    var q = new breeze.EntityQuery().from('categories').where('CatId', '==', node.id);
    manager.executeQuery(q).then(function (data) {
        data.results.forEach(function (item) {
            item.id = item.Id(); item.text = item.Name();
            if (item.SubCategories().length > 0) { item.state = 'closed'; } else { item.state = 'open'; }
            createNode(id, node, item.id, item.text, item.state, intab);
            var d = node.target.nextSibling;
            d.attributes.style.value = 'display : block';
        });
    }).fail(function (e) { alert(e); });
}
function createNode(treeid, parentnode, id, text, state, intab) {    
    if (intab) {
        var tab = $('#tablist').tabs('getSelected');
        var obj = tab.find("#" + treeid);
        $(obj).combotree('tree').tree('append', {
            parent: parentnode.target,
            data: [{
                id: id,
                text: text,
                state: state
            }]
        });
    } else {
        $("#" + treeid).combotree('tree').tree('append', {
            parent: parentnode.target,
            data: [{
                id: id,
                text: text,
                state: state
            }]
        });

    }
    
}

function addChild() {
    var categoryName = prompt("Please enter category name", "");
    var t = $('#categoryList').combotree('tree');
    var node = t.tree('getSelected');
    var newCategory = createCategory(categoryName);
    manager.addEntity(newCategory);
    t.tree('append', {
        parent: (node ? node.target : null),
        data: [{
            id: newCategory.id,
            text: categoryName
        }]
    });
    manager.saveChanges([newCategory]).then(function (data) {
        newCategory.Id(data.keyMappings[0].realValue);
        newCategory.id = newCategory.Id();
        //viewModel.categories.push(newCategory);
    });
}
function addCategory() {
    var categoryName = prompt("Please enter category name", "");
    var t = $('#categoryList').combotree('tree');
    var node = t.tree('getSelected');
    var parentnode = t.tree('getParent', node.target);
    var newCategory = createCategory(categoryName);
    //manager.addEntity(newCategory);
    

    t.tree('insert', {
        after: (node ? node.target : null),
        data: [{
            id: newCategory.id,
            text: categoryName
        }]
    });
    manager.saveChanges([newCategory]).then(function (data) {
        newCategory.Id(data.keyMappings[0].realValue);
        newCategory.id = newCategory.Id();
        viewModel.categories.push(newCategory);
    });

        

        
}
function removeCategory() {
    var t = $('#categoryList').combotree('tree');	// get the tree object
    var node = t.tree('getSelected');
    var selectedCategory = manager.getEntityByKey('Category', node.id);
    selectedCategory.entityAspect.setDeleted();

    manager.saveChanges().then(function (data) {
        viewModel.categories.remove(selectedCategory);
    });
}

function createCategory(categoryName) {
    var newvalue = $.trim(categoryName);
    if (newvalue == '') {
        alert('Please type category name');
        return null;
    } else {      
        //Add to viewmodel
        var newCategory = manager.createEntity('Category', { Name: newvalue, CatId:  });
        newCategory.id = newCategory.Id();
        newCategory.text = newvalue;
        return newCategory;
    }
}
function loadQuestion(query) {
    manager.executeQuery(query).then(function (data) {
        data.results.forEach(function (item) {
            item.id = item.Id();
            item.text = item.Title();
        });
        viewModel.questions(data.results);
    }).fail(function (e) {
        alert(e);
    });
}

function loadAnswer(query) {
    manager.executeQuery(query).then(function (data) {
        data.results.forEach(function (item) {
            item.id = item.Id();
            item.text = item.Title();
        });
        viewModel.answers(data.results);
    }).fail(function (e) {
        alert(e);
    });
}

function UpdateCategory() {
    //Remove old category
    for (var i = 0; i < vm.questiondetail.CategoryQuestions().length; i++) {
        var Item2Delete = vm.questiondetail.CategoryQuestions()[i];
        Item2Delete.entityAspect.setDeleted();
    }
    manager.saveChanges().fail(function (err) {
        alert(err);
    });
    for (var k = 0; k < vm.selectedcat().length; k++) {
        var id = vm.selectedcat()[k];
        var Newentity = manager.createEntity('CategoryQuestion', { AquestionId: CurrentQuestion, CategoryId: id });
        manager.addEntity(Newentity);
    }
}
